import * as types from '../mutation-types'
import http from '@/utils/http'
import {getToken, setToken, removeToken} from '@/utils/helpers'
import { asyncRouterMap, constantRouterMap } from '@/router'
export default {
  state: {
    token: getToken(),
    userInfo: null,
    routers: constantRouterMap,
    accessedRouters: []
  },
  getters: {
    token: state => state.token,
    userInfo: state => state.userInfo,
    permissions: state => {
      state.userInfo && state.userInfo.all_permissions ? state.userInfo.all_permissions : []
    },
    routers: state => state.routers,
    accessedRouters: state => state.accessedRouters
  },
  mutations: {
    [types.SET_TOKEN]: (state, token) => {
      setToken(token)
      state.token = token
    },
    [types.SET_USER_INFO]: (state, userInfo) => {
      state.userInfo = userInfo
    },
    [types.SET_ROUTERS]: (state, routers) => {
      state.accessedRouters = routers
      state.routers = constantRouterMap.concat(routers)
    }
  },
  actions: {
    login: ({ commit }, user) => {
      return new Promise((resolve, reject) => {
        http.post('/auth', user).then(response => {
          commit(types.SET_TOKEN, response.data.access_token)
          resolve()
        }).catch(error => {
          console.log(error)
          reject(error)
        })
      })
    },
    logout: ({commit, state}) => {
      return new Promise((resolve, reject) => {
        http.post('/logout', state.token).then(() => {
          commit(types.SET_TOKEN, '')
          removeToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    getUserInfo: ({commit, state}) => {
      return new Promise((resolve, reject) => {
        http.get('/user').then(response => {
          commit(types.SET_USER_INFO, response.data)
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },
    generateRoutes: ({commit}, permissions) => {
      return new Promise(resolve => {
        let accessedRouters = filterAsyncRouter(asyncRouterMap, permissions)
        commit(types.SET_ROUTERS, accessedRouters)
        resolve()
      })
    }
  }
}

/**
 * 通过meta.permission判断是否与当前用户权限匹配
 * @param permissions
 * @param route
 */
function hasPermission (permissions, route) {
  if (route.meta && route.meta.permission) {
    // return permissions.some(permission => route.meta.permission.indexOf(permission) >= 0)
    return permissions.some(permission => route.meta.permission === permission)
  } else {
    return true
  }
}

/**
 * 递归过滤异步路由表，返回符合用户权限的路由表
 * @param asyncRouterMap
 * @param permissions
 */
function filterAsyncRouter (asyncRouterMap, permissions) {
  const accessedRouters = asyncRouterMap.filter(route => {
    if (hasPermission(permissions, route)) {
      if (route.children && route.children.length) {
        route.children = filterAsyncRouter(route.children, permissions)
      }
      return true
    }
    return false
  })
  return accessedRouters
}
